package com.gwlc.common.util;

import org.bouncycastle.util.encoders.Hex;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * <p>lucky-com.gwlc.common.util-HashTool</p>
 * <p>Description:  </p>
 * <p>Copyright: Copyright (c) 2021</p>
 * <p>Company: hanchunit@163.com</p>
 *
 * @author hanchun
 * @version 1.0
 * @date
 */


public class HashTool {

    /**
     * HmacSHA256加密
     *
     * @param key  密钥
     * @param data 数据
     * @return 加密结果
     */
    public static String encode(String key, String data) {
        String code = null;
        try {
            Mac sha256HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            sha256HMAC.init(secretKey);
            code = Hex.toHexString(sha256HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            throw new RuntimeException("密码编码错误");
        }
        return code;
    }
}

